<template>
  <div class="search">
    <Card>
      <Row>
        <Form
          ref="editForm"
          :model="editForm"
          :rules="rules"
          style="width: 100%"
          :label-width="120"
        >
          <FormItem label="资讯标题" prop="title">
            <Input
              v-model="editForm.title"
              placeholder="请输入资讯标题"
              style="width: 40%"
            />
            <span style="margin: 15px">推荐显示</span
            ><i-switch
              v-model="editForm.recommendSort"
              :true-value="1"
              :false-value="-1"
              true-color="#5FB878"
            />
          </FormItem>
          <FormItem label="资讯类型" prop="type">
            <div
              v-for="(i, k) in typeList"
              :key="k"
              @click="handleCheck(k)"
              class="type-item"
              :class="{ typeCheck: i.checked }"
            >
              {{ i.label }}
            </div>
          </FormItem>
          <FormItem label="信息来源" prop="sourceType">
            <RadioGroup v-model="editForm.sourceType">
              <Radio :label="0">内部供稿</Radio>
              <Radio :label="1">外部网站</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem>
            <Input
              v-model="editForm.origin"
              style="width: 40%"
              placeholder="请输入信息来源，如网站、投稿人等"
            ></Input>
          </FormItem>
          <FormItem label="关键词" prop="keyword">
            <Input
              v-model="editForm.keyword"
              placeholder="请输入关键词，多个关键词时，英文逗号隔开"
              style="width: 40%"
            />
          </FormItem>
          <FormItem label="显示模式" v-if="editForm.resourceType == 1" prop="displayMode">
            <Select
              v-model="editForm.displayMode"
              placeholder="请选择显示模式"
              clearable
              style="width: 40%"
            >
              <Option v-for="(i, k) in modeList" :key="k" :value="i.value">{{
                i.label
              }}</Option>
            </Select>
          </FormItem>
          <FormItem
            v-if="editForm.resourceType == 1 && editForm.displayMode != 3"
            prop="coverPath"
          >
            <div class="form-img" v-for="(i, k) in imgList" :key="k">
              <img :src="i" />
              <Icon type="ios-close-circle" @click="handleDelImg(k)" />
            </div>
            <Upload
              v-if="uploadSHow"
              type="drag"
              ref="upload"
              multiple
              action
              :max-size="2 * 1024"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              accept=".jpg, .jpeg, .png"
              :format="['jpg', 'jpeg', 'png']"
              style="width: max-content; display: inline-block"
            >
              <div style="width: 150px; height: 150px; line-height: 150px">
                <Icon type="md-add" size="20" />
              </div>
            </Upload>
            <span v-if="editForm.displayMode == 1" style="margin-left: 20px; color: #aaa"
              >上传jpg/png格式图片，不超过2MB，支持上传1张</span
            >
            <span v-if="editForm.displayMode == 2" style="margin-left: 20px; color: #aaa"
              >上传jpg/png格式图片，每张图片不超过2MB，支持上传3张</span
            >
          </FormItem>
          <FormItem label="上传形式" prop="resourceType">
            <RadioGroup v-model="editForm.resourceType">
              <Radio :label="1">图文</Radio>
              <Radio :label="2">视频</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            label="资讯内容"
            :prop="editForm.resourceType == 1 ? 'details' : 'content'"
          >
            <Editor v-if="editForm.resourceType == 1" :defaultText="defaultText"   :richText.sync="editForm.details" style="max-width: 800px" />
            <div v-else>
              <video
                width="400"
                v-if="videoFlag && editForm.content"
                autoplay
                controls
                :poster="editForm.coverPath"
                :src="editForm.source"
                controlslist="nodownload"
              />
              <Upload
                action
                accept=".mp4"
                :format="['mp4']"
                ref="uploadVideo"
                :max-size="2 * 1024 * 1024"
                :show-upload-list="false"
                :before-upload="handleHttpRequest"
                style="display: inline-block"
              >
                <Button :loading="!videoFlag">{{ videoLabel }}</Button>
              </Upload>
              <Progress
                v-if="!videoFlag && isShow"
                style="width: 300px; margin-left: 10px"
                :percent="process"
                status="active"
              />
            </div>
          </FormItem>
          <div>
            <Button type="text" @click="toback">返回</Button>
            <Button type="primary" @click="submitForm">保存</Button>
          </div>
        </Form>
      </Row>
    </Card>
  </div>
</template>

<script>
import * as API_News from "@/api/news.js";

import Editor from '@/components/editor/WEditor.vue';
import { videoUrl, uploadCover } from "@/api/common.js";

import md5 from "@/utils/spark-md5";
import { verifyFile, initTask, preSignUrl, mergeChunks } from "@/api/chunkFile";
let chunkSize = 1024 * 1024 * 5; //分片大小

export default {
  name: "news-form",
  components: {
    Editor,
  },
  data() {
    return {
      defaultText:"",
      editForm: {}, // 表单
      imgList: [], //图片
      videoFlag: true, //视频刷新
      typeList: [
        // 资讯类型
        { value: "1003001", label: "政策法规", checked: false },
        { value: "1003002", label: "求职创业", checked: false },
        { value: "1003003", label: "运动处方", checked: false },
        { value: "1003004", label: "健康科普", checked: false },
        { value: "1003005", label: "其他", checked: false },
      ],
      modeList: [
        //显示模式
        { value: 1, label: "大图模式" },
        // { value: 2, label: "小图模式" },
        { value: 3, label: "普通模式" },
      ],
      rules: {
        // 验证规则
        title: [{ required: true, message: "请输入资讯标题" }],
        type: [{ required: true, message: "请选择资讯类型" }],
        sourceType: [{ required: true, message: "请选择信息来源" }],
        coverPath: [{ required: true, message: "请上传资讯封面" }],
        details: [{ required: true, message: "请输入资讯内容" }],
        content: [{ required: true, message: "请上传视频" }],
      },
      chunksList: [], // 用户选中文件的切片文件
      current: 0, //进度
      videoLabel: "上传",
      isShow: false, // 显示进度条
    };
  },
  computed: {
    uploadSHow: {
      get() {
        let res = true;
        if (this.editForm.displayMode == 1) {
          res = this.imgList.length == 0;
        }
        if (this.editForm.displayMode == 2) {
          res = this.imgList.length < 3;
        }
        return res;
      },
    },
    process: {
      get() {
        let z = this.current;
        let m = this.chunksList.length || 1;
        let r = (parseFloat(z / m) * 100).toFixed(2);
        return parseFloat(r);
      },
      set() {},
    }
  },
  mounted() {
    let id = this.$route.query.id;
    this.init(id);
  },
  methods: {
    // 返回上级
    toback() {
      this.$store.commit("removeTag", "news-form");
      this.$router.go(-1);
    },
    // 删除图片
    handleDelImg(k) {
      this.imgList.splice(k, 1);
      this.editForm.coverPath = this.imgList.join(",");
    },
    // 初始化表单
    init(id = null) {
      let form = {
        id: null,
        title: null, //资讯标题
        recommendSort: -1, //推荐显示 -1不推荐，1推荐
        type: null, //资讯类型
        sourceType: null, //资讯来源类型
        origin: null, //资讯来源
        keyword: null, //关键字
        displayMode: 1, //显示模式 1大图，2小图，3普通
        resourceType: 1, //上传形式 1图文，2视频
        details: null, //资讯内容
        content: null, // 临时资讯内容
        source: null, // 临时播放地址
        coverPath: "", // 资讯封面
        createByType: "1004002", //创建人类型1004001专家，1004002平台
      };
      if (id) {
        API_News.getNewsDetail(id).then((res) => {
          if (res.success) {
            this.editForm = Object.assign(form, res.result);
            this.typeList.forEach((i) => {
              i.checked = i.value == this.editForm.type;
            });
            if (this.editForm.resourceType == 2) {
              this.editForm.content = this.editForm.details;
              this.editForm.source = videoUrl(this.editForm.details);
            }else{
              this.$nextTick(()=>{
                this.defaultText=res.result.details
              })
            }
            if (this.editForm.resourceType == 1 && this.editForm.coverPath) {
              this.imgList = this.editForm.coverPath.split(",");
            }
          }
        });
      } else {
        this.editForm = Object.assign({}, form);
      }
      this.$refs.editForm.resetFields();
    },
    async getTaskInfo(file) {
      let task = null;
      let identifier = await md5(file);
      this.setVideoTip(false, "检查中");
      const { code, data } = await verifyFile(identifier);
      if (code == 200000) {
        task = data;
        if (!task) {
          const initTaskData = {
            identifier,
            fileName: file.name,
            totalSize: file.size,
            chunkSize,
          };
          const res = await initTask(initTaskData);
          if (res.code == 200000) {
            task = res.data;
          } else {
            this.setVideoTip();
            this.$Message.warning(res.msg);
          }
        } else {
          this.setVideoTip();
        }
      }
      return task;
    },
    setVideoTip(flag = true, label = "上传") {
      this.videoFlag = flag;
      this.videoLabel = label;
    },
    // 分片上传
    async handleUpload(file, taskRecord) {
      let start = 0; // 切片文件的起始位置
      while (start < file.size) {
        const chunkItem = file.slice(start, start + chunkSize);
        this.chunksList.push(chunkItem);
        start += chunkSize;
      }
      let identifier = taskRecord.fileIdentifier;
      let requestList = [];
      for (let i = 0; i < taskRecord.chunkNum; i++) {
        requestList.push(preSignUrl(this.chunksList, identifier, i + 1));
      }
      requestList.map((item) => {
        item.then(() => {
          this.current++;
        });
      });
      // 等待所有切片上传完成
      await Promise.all(requestList);
      this.setVideoTip(false, "合并中");
      mergeChunks(identifier).then((result) => {
        if (result.code == 200) {
          this.uploadCoverPath(file);
          this.editForm.content = result.result.location;
          this.editForm.source = videoUrl(result.result.location);
          this.setVideoTip();
          this.isShow = false;
          this.current = 0;
          this.chunksList = [];
        }
      });
    },
    // 自定义上传视频
    handleHttpRequest(file) {
      if (file.name.lastIndexOf(".mp4") == -1) {
        this.$Message.warning("只支持上传MP4格式视频");
        return;
      }
      if (file.size / 1024 > 2 * 1024 * 1024) {
        this.$Message.warning("视频大小不能超过2GB");
        return;
      }
      if (file.size / 1024 > 3 * 1024) {
        this.isShow = true;
        this.handleMaxVideo(file);
      } else {
        this.isShow = false;
        this.handleMinVideo(file);
      }
      return false;
    },
    // 小文件视频上传
    handleMinVideo(file) {
      this.setVideoTip(false, "上传中");
      const formData = new FormData();
      formData.append("file", file);
      API_News.postUpload(formData)
        .then((res) => {
          if (res.success) {
            this.editForm.content = res.result;
            this.editForm.source = videoUrl(res.result);
            this.uploadCoverPath(file);
          }
        })
        .finally(() => {
          this.$nextTick(() => {
            this.setVideoTip();
          });
        });
    },
    // 上传封面图
    async uploadCoverPath (file) {
      const path = await uploadCover(file)
      this.beforeUpload(path);
    },
    // 大文件视频上传
    async handleMaxVideo(file) {
      this.setVideoTip(false, "准备中");
      const task = await this.getTaskInfo(file);
      this.setVideoTip(false, "上传中");
      if (task) {
        const { finished, path, taskRecord } = task;
        if (finished) {
          this.editForm.content = path;
          this.editForm.source = videoUrl(path);
          this.uploadCoverPath(file);
          this.setVideoTip();
          this.isShow = false;
          this.current = 0;
        } else {
          await this.handleUpload(file, taskRecord);
        }
      } else {
        this.setVideoTip(true, "上传失败");
        this.isShow = false;
        this.current = 0;
      }
    },
    // 自定义上传
    beforeUpload(file) {
      let typeList = [".jpg", ".jpeg", ".png"];
      if (!typeList.some((i) => file.name.lastIndexOf(i) != -1)) {
        this.$Message.warning("请检查上传文件格式");
        return;
      }
      if (file.size / 1024 > 2 * 1024) {
        this.$Message.warning("图片大小不能超过2MB");
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      API_News.postUpload(formData).then((res) => {
        if (res.success) {
          if (this.editForm.displayMode == 1) {
            if (this.imgList.length == 0) {
              this.imgList.push(res.result);
              this.editForm.coverPath = this.imgList.join(",");
            }
          }
          if (this.editForm.displayMode == 2) {
            if (this.imgList.length < 3) {
              this.imgList.push(res.result);
              this.editForm.coverPath = this.imgList.join(",");
            }
          }
          if (this.editForm.displayMode == 3) {
            this.imgList =[res.result];
            this.editForm.coverPath = res.result;
          }
        }
      });
      return false;
    },
    // 选择类型
    handleCheck(index) {
      this.typeList.forEach((i, k) => {
        if (k == index) {
          i.checked = true;
          this.editForm.type = i.value;
        } else {
          i.checked = false;
        }
      });
    },
    //提交
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editForm.displayMode == 3 && this.editForm.resourceType == 1) {
            this.editForm.coverPath = "";
          }
          let data = Object.assign({}, this.editForm);
          if (data.resourceType == 1) {
            let text = this.replaceHTML(data.details);
            if (text && text.length > 10000) {
              this.$Message.warning(`当前字数为${text.length}字，字数不能超过10000字`);
              return;
            }
          } else {
            data.details = data.content;
            data.displayMode = 3;
            this.editForm.coverPath = "";
          }
          delete data.content;
          delete data.source;
          if (this.editForm.id) {
            API_News.postNewsUpdate(data).then((res) => {
              if (res.success) {
                this.$Message.success("修改成功");
                this.toback();
              }
            });
          } else {
            API_News.postNewsSave(data).then((res) => {
              if (res.success) {
                this.$Message.success("添加成功");
                this.toback();
              }
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss">
.tox.tox-tinymce.tox-fullscreen {
  top: 110px !important;
  left: 190px !important;
  width: calc(100% - 202px) !important;
  height: calc(100% - 122px) !important;
}
</style>
<style lang="scss" scoped>
.type-item {
  user-select: none;
  display: inline-block;
  padding: 0 15px;
  border: 1px solid transparent;
  border-radius: 4px;
  margin-right: 5px;
  background-color: #f5f5f5;
  &:hover {
    cursor: pointer;
    color: #20dfdf;
    border: 1px solid #5dd6c9;
    background-color: #ffffff;
  }
}
.typeCheck {
  color: #20dfdf;
  border: 1px solid #caf1ed;
  background-color: #edfaf9;
}
.form-img {
  width: 150px;
  height: 150px;
  margin-right: 10px;
  display: inline-block;
  position: relative;
  img {
    width: 100%;
    height: 100%;
    border-radius: 4px;
  }
  ::v-deep(.ivu-icon) {
    position: absolute;
    top: -9px;
    right: -9px;
    font-size: 20px;
    background-color: #fff;
    border-radius: 50%;
    &:hover {
      cursor: pointer;
      color: #a3a3a3;
    }
  }
}
video {
  background-color: #000;
  vertical-align: bottom;
  margin-right: 20px;
}
</style>
